/*
 * Copyright 2007, 2008 Tiberiumlabs
 *
 * This file is part of Tiberiumlabs Lailaps.
 *
 * Tiberiumlabs Lailaps is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tiberiumlabs Lailaps is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tiberiumlabs.lailaps.threads;

import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tiberiumlabs.lailaps.Mediator;
import org.tiberiumlabs.lailaps.actions.events.DataEvent;
import org.tiberiumlabs.lailaps.actions.events.DataListener;
import org.tiberiumlabs.lailaps.list.DownloadItem;
import org.tiberiumlabs.lailaps.list.DownloadsListModel;
import org.tiberiumlabs.lailaps.settings.NetworkSettings;
import org.tiberiumlabs.lailaps.settings.Settings;

/**
 * TODO: think about row changes in currently executing items
 * 
 * @author <a href="paranoid.tiberiumlabs@gmail.com">Paranoid</a>
 */
public class DownloadManager implements DataListener {

    private static final Log LOG = LogFactory.getLog(DownloadManager.class);
    private final PriorityQueue<ListItem> itemsQueue = new PriorityQueue<ListItem>();
    private final Object lock = new Object();
    private int running = 0;
    private final NetworkSettings networkSettings = Settings.getNetworkSettings();
    private ExecutorService executor;

    public void add(DownloadItem item, int row) {
        synchronized (itemsQueue) {
            itemsQueue.offer(new ListItem(item, row));
        }
        mayBeRun();
    }

    public void remove(int row) {
        synchronized (itemsQueue) {
            itemsQueue.remove(new ListItem(null, row));
        }
    }

    private void mayBeRun() {
        int maxRunning = networkSettings.getMaxWorkingThreads();
        synchronized (lock) {
            if (running == maxRunning) {
                return;
            }
            while (running < maxRunning) {
                running++;
                ListItem item;
                synchronized (itemsQueue) {
                    item = itemsQueue.poll();
                }
                run(item);
            }
        }
    }

    private void run(ListItem item) {
        // TODO implement
        execute(new Runnable() {
            public void run() {
                work();
            }
        });
    }
    
    public void execute(Runnable runnable) {
        if (executor == null) {
            int threadsCount = networkSettings.getMaxWorkingThreads() * networkSettings.getMaxSegmentsPerThread();
            executor = Executors.newFixedThreadPool(threadsCount, new DownloadThreadFactory());
        }
        executor.execute(runnable);
    }

    /**
     * Method to execute in thread pool.
     */
    private void work() {
            try {
                // TODO process all the download
            } catch (Exception ex) {
                LOG.warn("[ DOWNLOADS ] Exception in DownloadManager worker", ex);
            } finally {
                synchronized (lock) {
                    running--;
                }
                mayBeRun();
            }
    }

    public void dataChanged(DataEvent event) {
        if (itemsQueue.isEmpty()) {
            return;
        }
        DownloadsListModel model = Mediator.getMediator().getDownloadsListModel();
        Iterator<ListItem> iterator = itemsQueue.iterator();
        while (iterator.hasNext()) {
            ListItem item = iterator.next();
            item.row = event.calculateCurrentRow(item.row);
            if (item.row == -1 && item.item != null) {
                item.row = model.indexOfItem(item.item);
            }
        }
    }

    public static final class ListItem implements Comparable<ListItem> {

        private final DownloadItem item;
        private int row;

        public ListItem(DownloadItem item, int row) {
            this.item = item;
            this.row = row;
        }

        public DownloadItem getItem() {
            return item;
        }

        public int getRow() {
            return row;
        }

        public void setRow(int row) {
            this.row = row;
        }

        public int compareTo(ListItem o) {
            return this.row - o.row;
        }

        @Override
        public boolean equals(Object obj) {
            try {
                ListItem i = (ListItem)obj;
                return row == i.row;
            } catch (Exception ex) {
            }
            return false;
        }

        @Override
        public int hashCode() {
            return row;
        }

    }

    private static final class DownloadThreadFactory implements ThreadFactory {

        private int priority = Thread.NORM_PRIORITY - 2;
        private int count = 1;

        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, "Lailaps download " + count++);
            if (!thread.isDaemon()) {
                thread.setDaemon(true);
            }
            if (thread.getPriority() != priority) {
                thread.setPriority(priority);
            }
            LOG.debug("[ DOWNLOADS ] New Download thread created.");
            return thread;
        }

    }

}
